﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WatchDog
{
    public partial class AddRange : Form
    {
        #region C'tor
        public AddRange()
        {
            InitializeComponent();
            this.okButton.Enabled = false;
        }
        #endregion C'tor

        #region Members
        private const string IpPattern = @"\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?";
        private readonly List<string> ips = new List<string>();
        internal List<string> IPList
        {
            get { return this.ips; }
        }
        #endregion Members

        #region Methods

        private void IpAddressTextBoxTextChanged(object sender, EventArgs e)
        {
            var regex = new Regex(IpPattern);
            bool isMatch = regex.IsMatch(this.ipAddressTextBox.Text);
            if(!isMatch)
            {
                this.okButton.Enabled = false;
                this.ipAddressTextBox.ForeColor = Color.Red;
            }
            else
            {
                this.okButton.Enabled = true;
                this.ipAddressTextBox.ForeColor = Color.Black;
            }
        }

        private void OkButtonClick(object sender, EventArgs e)
        {
            var ip = this.ipAddressTextBox.Text;
            ips.Clear();
            ips.Add(ip);
            if (numericUpDown1.Value > 0)
            {
                var newIp = ip;
                for (int i = 1; i < numericUpDown1.Value; i++)
                {
                    int index = newIp.LastIndexOf('.');
                    int lastNumber = Int32.Parse(newIp.Substring(index + 1));
                    if (lastNumber == 255) lastNumber = -1;
                    newIp = newIp.Substring(0, index + 1) + (++lastNumber);
                    ips.Add(newIp);
                }
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void CancelButtonClick(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        #endregion Methods
    }
}
